const url = getApp().globalData.API_URL;
const Uid =  getApp().globalData.uid;
Component({
  data: {
    monthShouru: '0.00',
    monthZhichu: '0.00',
    currentMonth: '1',
    currentDay: '1',
    currentYear: '2000',
    chooseMonth: '1',
    chooseYear: '2000',
    chooseDay: '1',
    allDatas:[],
    thisMonthData:[],
    type:0
  },
  attached(){
    this.init();
  },
  pageLifetimes:{
    show(){
      this.getAllDatas();
    }
  },
  methods: {
    //为时间、总收入、总支出等数据初赋值
    init() {
      var date = new Date();
      this.setData({
        currentYear:date.getFullYear(),
        currentMonth:date.getMonth() + 1,
        currentDay:date.getDate(),
        chooseYear:date.getFullYear(),
        chooseMonth:date.getMonth() + 1,
        chooseDay:date.getDate()
      })
    },
    //计算总收入总支出
    getDataCache() {
      try {
        var monthShouruTemp = 0;
        var monthZhichuTemp = 0;
        let _this = this;
        var MonthDataTmp = this.data.allDatas.filter(function (data) {
          let year = new Date(data.date).getFullYear();
          let month = new Date(data.date).getMonth()+1;
          return year == _this.data.chooseYear && month == _this.data.chooseMonth;
        })
          for (var data of MonthDataTmp) {
            if (data.caloricSum > 0) {
              monthShouruTemp = parseFloat(monthShouruTemp) + parseFloat(data.caloricSum);
            } else {
              monthZhichuTemp = parseFloat(monthZhichuTemp) + parseFloat(data.caloricSum);
            }
          }
        this.setData({
          monthShouru : parseFloat(monthShouruTemp).toFixed(2),
          monthZhichu : parseFloat(-monthZhichuTemp).toFixed(2),
        })
      } catch (e) {
        console.log(e);
      };
    },
    //日期选择器
    bindMonthChange(e) {
      var date = new Date(e.detail.value);
      this.setData({
        chooseMonth:date.getMonth()+1,
        chooseYear:date.getFullYear()
      })
      this.getThisMonthData();
      this.getDataCache(); 
    },
    //从后端拉取全部数据
    getAllDatas() {
      let _this = this;
      try {
        var uid = wx.getStorageSync('token');
      } catch (e) {
        console.log(e);
      }
      wx.request({
        url: `${url}/sys-detail/selectAllDetailsByUid/${uid}`,
        method: 'GET',
        success(res) {
          var datas = res.data;
          for (var data of datas) {
            data.caloricSum = parseFloat(data.caloricSum / 100).toFixed(2);
            var year = data.date.slice(0,4);
            var month = data.date.slice(4,6);
            var day = data.date.slice(6,8);
            data.date = year+'-'+month+'-'+day;
            data.name = data.name.trim();
            data.specification = data.specification.trim();
            data.info = data.info.trim();
          }
          _this.setData({
            allDatas: datas
          })
          _this.getThisMonthData();
          _this.getDataCache();
        },
        fail(){
          console.log("fail");
        }
      })
    },
    //过滤出选择日期对应的数据
    getThisMonthData(){
      var _this = this;
      var allDatas = this.data.allDatas;
      var thisMonthData=[];
      thisMonthData = allDatas.filter(function (data) {
        var year = new Date(data.date).getFullYear();
        var month = new Date(data.date).getMonth()+1;
        return year == _this.data.chooseYear && month == _this.data.chooseMonth;
      })
      if(this.data.type === '1'){
        thisMonthData=thisMonthData.filter(function (data) {
          return data.caloricSum>0;
        });
      }else if(this.data.type === '2'){
        thisMonthData=thisMonthData.filter(function (data) {
          return data.caloricSum<0;
        })
      }
      thisMonthData.sort(function (a,b) {
          if(a.date == b.date){
            return a.caloricSum - b.caloricSum;
          }else{
            return new Date(b.date) - new Date(a.date);
          }
      })
      this.setData({
        thisMonthData:thisMonthData
      })
    },
    //定位长按删除
    showDeleteConfirm(event){
      var index = event.currentTarget.dataset.index;
      wx.showModal({
        title: '确认删除',
        content: '确定要删除此记录吗？',
        success: (res) => { 
          if (res.confirm) {
            // 如果用户确认删除，执行删除操作
            this.deleteRecord(index);
          }
        }
      });
    },
    //删除
    deleteRecord(index){
      var did = this.data.thisMonthData[index].did;
      let _this = this;
      console.log(did);
      wx.request({
        url: `${url}/sys-detail/del/${did}`,
        method:'DELETE',
        success(res){
          console.log(res.data);
          var allDatas = _this.data.allDatas;
          allDatas = allDatas.filter(function (data) {
            return data.did != did;
          })
          _this.setData({
            allDatas:allDatas
          })
          _this.getThisMonthData();
          _this.getDataCache()
        },
        fail(){
          console.log("fail");
        }
      })
    },

    // 类别获取
    onTabsClick(event) {
      this.setData({
        type: event.detail.value
      });
      this.getThisMonthData();
    },

    // 详情查看
    toDataInfo(event) {
      const index = event.currentTarget.dataset.index;
      const dataInfo = JSON.stringify(this.data.thisMonthData[index]); // 将对象转换为字符串
      wx.navigateTo({
        // 对字符串进编码
        url: `../goodsEdit/goodsEdit?dataInfo=${encodeURIComponent(dataInfo)}`, 
      });
    },

    // 添加新账单
    toAdd() {
      wx.navigateTo({
        url: '../goodsAdd/goodsAdd',
      })
    },
  },
});